package chaw.android.train.MoreActivities;

import java.util.ArrayList;
import java.util.ListIterator;

import chaw.android.train.MoreActivity;
import chaw.android.train.R;
import chaw.android.train.TrainTravelActivity;
import chaw.android.util.ContactsItem;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MoreAnnounceActivity extends ListActivity {
	private ContactsItemAdapter adapter;
	private ArrayList<ContactsItem> contactsList, selectedList;
	private ImageView btnShare, btnBack;
	
    String result;

	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.more_announce);
	    
	    btnShare = (ImageView) findViewById(R.id.btnShare);
	    btnBack = (ImageView) findViewById(R.id.btnBack);
	    
	    btnShare.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				share();
			}
		});
	    
	    btnBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				MoreActivity parentActivity = (MoreActivity)getParent();
				parentActivity.finishFromChild(MoreAnnounceActivity.this);
			}
		});
	}
	
	private void share(){
		if(selectedList.isEmpty())
			Toast.makeText(getBaseContext(), "선택한 사람이 없습니다.", Toast.LENGTH_SHORT).show();
		else{
			ListIterator<ContactsItem> contactsIter = selectedList.listIterator();
			while(contactsIter.hasNext()){
				String eachNumber = contactsIter.next().getNumber();
				String text = "<앱소개> - 낭만 기차여행자들의 광장! http://www.traintravelers.co.kr";
				
				PendingIntent pend = PendingIntent.getActivity(this, 0, new Intent(this, TrainTravelActivity.class), 0);
				SmsManager sms = SmsManager.getDefault();
				sms.sendTextMessage(eachNumber, null, text, pend, null);
			}
			Toast.makeText(getBaseContext(), selectedList.size() + "명에게 공유했습니다.", Toast.LENGTH_SHORT).show();
		}
	}

	private void setListView(){
		contactsList = new ArrayList<ContactsItem>();
		contactsList.clear();
		
		DownloadAsynkTask task = new DownloadAsynkTask();
		task.execute(new String[]{});
	}	
	
	@Override
	public void onListItemClick(ListView parent, View v, int position, long id){
		ContactsItem selectedItem = contactsList.get(position);
		
		if(selectedList.contains(selectedItem)){
			selectedList.remove(selectedItem);
			selectedItem.setIconBeforeAdd();
		}
		else{
			selectedList.add(selectedItem);
			selectedItem.setIconAfterAdd();
		}

		contactsList.set(position, selectedItem);
		adapter.notifyDataSetChanged();
	}
	
	private class ContactsItemAdapter extends ArrayAdapter<ContactsItem>{
		private ArrayList<ContactsItem> items;
		
		public ContactsItemAdapter(Context ctx, int rsrcId, ArrayList<ContactsItem> data){
			super(ctx, rsrcId, data);
			this.items = data;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent){
			View v = convertView;
			if(v == null){
				LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = li.inflate(R.layout.more_announce_list_row, null);
			}
			ContactsItem e = items.get(position);
			if(e != null){
				String name;
				if(e.getName().length() > 8)
					name = e.getName().substring(0, 8) + "...";
				else
					name = e.getName();
				((TextView)v.findViewById(R.id.moreAnnounceName)).setText(name);
				((TextView)v.findViewById(R.id.moreAnnounceNumber)).setText(e.getNumber());
				((ImageView)v.findViewById(R.id.moreAnnounceIcon)).setImageResource(e.getIcon());
			}
			return v;
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		selectedList = new ArrayList<ContactsItem>();
		selectedList.clear();
		setListView();
		for(int i = 0 ; i < 5; i++)
        	TrainTravelActivity.tabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.drawable.bg_nav1);
	}
	
	private class DownloadAsynkTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			String response = null;
			
			String[] projection = new String[] { Contacts._ID, Contacts.DISPLAY_NAME, Contacts.HAS_PHONE_NUMBER };
		    String selection = Contacts.HAS_PHONE_NUMBER + "=?";
		    String[] selectinoArgs = new String[] { "1" };
		    String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
		    Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, projection, selection, selectinoArgs, sortOrder);
		    
		    while(cursor.moveToNext()){
		    	String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
		    	String phoneSelection = ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?";
		    	String[] phoneSelectionArgs = new String[] { contactId };
		    	Cursor phones = managedQuery(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, phoneSelection, phoneSelectionArgs, null);
		    	
		    	while(phones.moveToNext()){
		    		String eachPhoneNumber = phones.getString( phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
		    		String eachName = phones.getString( phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
		    		String eachId = phones.getString( phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone._ID));
		            ContactsItem eachContacts = new ContactsItem(eachName, eachPhoneNumber, eachId);
		            contactsList.add(eachContacts);
		    	}
		    }
			return response;
		}
		
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			adapter = new ContactsItemAdapter(getBaseContext(), R.layout.more_announce_list_row, contactsList);
			setListAdapter(adapter);
		}
	}
}
